from flask import Flask, render_template
from collections import Counter
import db

app = Flask(__name__)


@app.route('/')
def index():
    all_mods = db.fetch_all_mods()

    for mod in all_mods:
        if 'mod标签' in mod and mod['mod标签']:
            mod['mod标签'] = [tag.strip() for tag in mod['mod标签'].split(',')]
        else:
            mod['mod标签'] = []
    return render_template('index.html', mods=all_mods)

@app.route('/echarts')
def echarts():
    mods = db.fetch_all_mods()

    # 饼图数据
    legend_data = [mod['mod名称'] for mod in mods]
    series_data = [
        {
            'name': mod['mod名称'],
            'value': int(mod['mod浏览量']) if mod['mod浏览量'] else 0
        }
        for mod in mods
    ]

    # 词云图数据
    all_tags = []
    for mod in mods:
        tags = mod.get('mod标签', '')
        if tags:
            tag_list = [tag.strip() for tag in tags.split(',')]
            all_tags.extend(tag_list)

    tag_counts = Counter(all_tags)
    tag_data = [{'name': tag, 'value': count} for tag, count in tag_counts.items()]

    # 散点图数据
    scatter_data = []
    for mod in mods:
        red = int(mod.get('红票', 0))
        black = int(mod.get('黑票', 0))
        scatter_data.append({
            'name': mod['mod名称'],
            'value': [red, black]
        })

    # 新增散点图数据
    return render_template(
        'echarts.html',
        legend_data=legend_data,
        series_data=series_data,
        tag_data=tag_data,
        scatter_data=scatter_data
    )

if __name__ == '__main__':
    app.run(debug=True)
